﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Crawsome
{
    class RequestMaster
    {
        /// <summary>
        /// Sends POST Request
        /// </summary>
        /// <param name="URL">A web URL</param>
        /// <param name="POSTdata">POST Data</param>
        /// <returns>HTTP Response as string if WebRequest was valid, else returns error string.</returns>
        public static string POST(string URL, string POSTdata)
        {
            try
            {
                WebRequest request = WebRequest.Create(URL);
                request.Method = "POST";
                string postData = POSTdata;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                WebResponse response = request.GetResponse();
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();
                return responseFromServer;
            }
            catch (WebException e)
            {
                return e.Message;
            }
        }
    
        /// <summary>
        /// Sends GET Request
        /// </summary>
        /// <param name="URL">A web URL</param>
        /// <returns>HTTP Response as string if WebRequest was valid, else returns error string.</returns>
        public static string GET(string URL)
        {
            try
            {
                string responseFromServer = null;
                WebRequest request = WebRequest.Create(URL);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
                responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();
                return responseFromServer;
            }
            catch (WebException e)
            {
                return e.Message;
            }
        }
    }
}
